package cn.ljy.authority.config.security;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * token的工具类
 */
public class TokenUtil {
    /**
     * 根据header或参数中获取token
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("access_token");//读取token的值
        if (!StringUtils.hasLength(token)) {
            token = request.getParameter("access_token");
        }
        return token;
    }

    /**
     * 根据header或参数中获取前台的token
     * @return token
     */
    public static String getAppToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("app_token");//读取token的值
        if (!StringUtils.hasLength(token)) {
            token = request.getParameter("app_token");
        }
        return token;
    }

    /**
     * 从websocket中获取token
     * @return
     */
    public static String getAppTokenFromWebSocket(HttpServletRequest request) {
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //读取前台token的值,websocket必须通过Sec-WebSocket-Protocol读取
        String token = request.getHeader("Sec-WebSocket-Protocol");//读取token的值
        if (!StringUtils.hasLength(token)) {
            //这里表示通过地址栏传值
            token = request.getParameter("app_token");
        }
        return token;
    }

    /**
     * 专门设计的针对websocket
     * @return token
     */
/*    public static String getAppTokenOfWebsocket() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("lcvc-WebSocket");//读取token的值
        if (!StringUtils.hasLength(token)) {
            token = request.getParameter("lcvc-WebSocket");
        }
        return token;
    }*/
}
